package com.fagejiang.security.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fagejiang.security.entity.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

/**
 * TODO
 *
 * @author 发哥讲Java
 * @version 1.0
 * @date 2021-05-18 16:56
 */
@Service
public class UserServiceImpl implements UserDetailsService {
    @Autowired
    UsersService usersService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println("用户传过来的 username = " + username);
        // 如果 账号 username 不存在, 在数据库里面没有查询到则 抛出异常即可
        if (ObjectUtils.isEmpty(username)) {
            throw new UsernameNotFoundException(username + "账号不存在!");
        }
        // 开始查询数据库, 得到 数据库当前 username 对应的用户
        Users users = usersService.getOne(new QueryWrapper<Users>().eq("username", username));
        if (users == null) {
            throw new UsernameNotFoundException(username + "账号不存在!");
        }
        String pwd123 = new BCryptPasswordEncoder().encode("123");
        pwd123 = users.getPassword();
        return new User(username, pwd123, AuthorityUtils.createAuthorityList("admin"));
    }
}
